<template>
  <div v-if="formKey">
    <div
      v-for="(item, index) in list"
      :style="{
        display:
          item.columnName == formKey + '__' + primaryKeyFieldObj[formKey]
            ? 'none'
            : '',
      }"
      :key="index"
      class="item"
    >
      <el-checkbox v-model="item.checked" style="margin-right: 10px" />
      <div style="width: 100px">{{ item.columnTitle }}</div>
      别名：<el-input
        placeholder="选填，导入数据的标题"
        v-model="item.aliasTitle"
        clearable
        style="width: 200px"
      />
    </div>
    <span style="color: red">{{ errorTips }}</span>
  </div>
</template>
<script setup name='MainSet'>
const emits = defineEmits(["setJson"]);
const props = defineProps({
  formKey: {
    type: String,
    defulat: "",
  },
  formColumns: {
    type: Object,
    defulat: () => {},
  },
  primaryKeyFieldObj: {
    type: Object,
    defulat: () => {},
  },
  main: {
    type: Object,
    defulat: () => {},
  },
});
watch(
  () => props.formKey,
  (newVal, oldVal) => {
    if (newVal) {
      reset();
    }
  }
);
watch(
  () => props.formColumns,
  (newVal, oldVal) => {
    if (newVal&&newVal[props.formKey]) {
      reset();
    }
  },
  {
    deep: true,
    immediate: true
  }
);
const list = $ref([]),
  errorTips = $ref("");

setTimeout(() => {
  reset();
}, 1000);

function reset() {
  if (!props.formColumns[props.formKey]) {
    return;
  }
  let objs = {};
  if (props.main && props.main.list && props.main.list.length) {
    props.main.list.forEach((item) => {
      objs[item.columnName] = item;
    });
  }
  list = props.formColumns[props.formKey].map((item) => {
    return {
      columnName: item.columnName,
      columnTitle: item.columnTitle,
      aliasTitle: objs[item.columnName] ? objs[item.columnName].aliasTitle : "",
      checked: objs[item.columnName] ? objs[item.columnName].checked : false,
    };
  });
}
function submit() {
  errorTips = "请至少勾选一个字段";
  list.some((item) => {
    if (item.checked) {
      errorTips = "";
      return true;
    }
  });
  if (!errorTips) {
    emits("setJson", {
      tabType: "main",
      formData: { list: list },
    });
  }
}

defineExpose({
  submit,
});
</script>
<style lang='scss' scoped>
  .item {
    width: 100%;
    float: left;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
  }
</style>
